<template>
  <div class="failed-messages"><!-- 页面标题和操作区域 -->
    <div class="header-actions">
      <h2>失败消息列表</h2>
    </div>
    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="消息类型">
          <el-select v-model="filterForm.messageType" placeholder="请选择消息类型" clearable style="width: 200px" @change="handleFilterChange">
            <el-option label="全部" value=""/>
            <el-option v-for="type in messageTypes" :key="type" :label="type" :value="type"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable style="width: 150px" @change="handleFilterChange">
            <el-option label="全部" value=""/>
            <el-option label="失败" value="FAILED"/>
            <el-option label="已忽略" value="IGNORED"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button type="warning" @click="retryAllMessages" :disabled="pagination.total === 0">
        <el-icon>
          <Refresh/>
        </el-icon>
        重试所有
      </el-button>
    </div>
    <el-table :data="messages" border stripe :max-height="700" style="width: 100%" v-loading="loading">
      <el-table-column type="index" label="序号" width="80"/>
      <el-table-column prop="exchangeName" label="交换机" width="120"/>
      <el-table-column prop="routingKey" label="路由键" width="120"/>
      <el-table-column prop="messageType" label="消息类型" width="120"/>
      <el-table-column label="消息体" width="auto">
        <template #default="scope">
          <div 
            class="message-content-cell" 
            @click="copyToClipboard(scope.row.messageContent)"
            :title="scope.row.messageContent"
          >
            {{ scope.row.messageContent }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="failReason" label="失败原因" show-overflow-tooltip width="120"/>
      <el-table-column label="失败时间" width="160">
        <template #default="scope">{{ formatDateTime(scope.row.failTime) }}</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="110">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'IGNORED' ? 'info' : 'warning'">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button size="small" type="success" @click="retryMessage(scope.row.id)" v-if="scope.row.status !== 'IGNORED'">重试</el-button>
          <el-button size="small" type="warning" @click="ignoreMessage(scope.row.id)" v-if="scope.row.status !== 'IGNORED'">忽略</el-button>
          <el-button size="small" type="danger" @click="deleteMessage(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table><!-- 分页 -->
    <div class="pagination-wrapper" v-if="pagination.total > 0">
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize" :page-sizes="[10, 20, 50, 100]"
                     :total="pagination.total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"/>
    </div>
  </div>
</template>

<script setup>
import {inject, onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Refresh} from '@element-plus/icons-vue'
import {failedMessageApi, messageApi} from '../api'

const globalStore = inject('globalStore')

const messages = ref([])
const loading = ref(false)

// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 筛选表单
const filterForm = ref({
  messageType: '',
  status: ''
})

// 消息类型列表
const messageTypes = ref([])

// 加载失败消息列表
const loadFailedMessages = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      messageType: filterForm.value.messageType || undefined,
      status: filterForm.value.status || undefined
    }

    const data = await failedMessageApi.getList(params)
    messages.value = data.content || data.list || data

    // 更新分页信息
    if (data.totalElements !== undefined) {
      pagination.value.total = data.totalElements
    } else if (data.total !== undefined) {
      pagination.value.total = data.total
    } else if (Array.isArray(data)) {
      pagination.value.total = data.length
    }


  } catch (error) {
    ElMessage.error('加载失败消息失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 加载消息类型列表
const loadMessageTypes = async () => {
  try {
    const types = await messageApi.getTypes()
    messageTypes.value = Array.isArray(types) ? types : []
  } catch (error) {
    console.warn('加载消息类型失败:', error.message)
    // 如果API调用失败，使用默认的消息类型
    messageTypes.value = ['ORDER', 'PAYMENT', 'NOTIFICATION', 'USER', 'SYSTEM']
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  loadFailedMessages()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  loadFailedMessages()
}

// 筛选条件改变
const handleFilterChange = () => {
  pagination.value.currentPage = 1
  loadFailedMessages()
}

// 搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  loadFailedMessages()
}

// 重置筛选条件
const handleReset = () => {
  filterForm.value = {
    messageType: '',
    status: ''
  }
  pagination.value.currentPage = 1
  loadFailedMessages()
}

// 重试消息
const retryMessage = async (id) => {
  loading.value = true
  try {
    await failedMessageApi.retry(id)
    ElMessage.success('消息重试成功')
    await loadFailedMessages()
  } catch (error) {
    ElMessage.error('消息重试失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 忽略消息
const ignoreMessage = async (id) => {
  loading.value = true
  try {
    await failedMessageApi.ignore(id)
    ElMessage.success('消息已忽略')
    await loadFailedMessages()
  } catch (error) {
    ElMessage.error('消息忽略失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 删除消息
const deleteMessage = async (id) => {
  try {
    await ElMessageBox.confirm(
        '确定要删除这条失败消息吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    loading.value = true
    await failedMessageApi.delete(id)
    ElMessage.success('消息删除成功')
    await loadFailedMessages()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除消息失败: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}

// 重试所有消息
const retryAllMessages = async () => {
  try {
    await ElMessageBox.confirm(
        '确定要重试所有失败消息吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    loading.value = true
    const result = await failedMessageApi.retryAll()
    ElMessage.success(`成功重试${result.successCount}条消息`)
    await loadFailedMessages()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重试所有消息失败: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleString()
}

// 获取状态中文显示
const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '待处理',
    'IGNORED': '已忽略',
    'RETRY_FAILED': '重试失败',
    'PROCESSING': '处理中',
    'COMPLETED': '已完成'
  }
  return statusMap[status] || status
}

// 复制到剪切板
const copyToClipboard = async (text) => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
    } else {
      // 降级方案
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      document.execCommand('copy')
      textArea.remove()
    }
    ElMessage.success('消息内容已复制到剪切板')
  } catch (error) {
    ElMessage.error('复制失败: ' + error.message)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadMessageTypes()
  loadFailedMessages()
})
</script>

<style scoped>
.failed-messages {
  background: #f5f7fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 20px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e4e7ed;
}

.header-actions h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.header-actions h2::before {
  content: '';
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #409eff, #67c23a);
  border-radius: 2px;
  margin-right: 12px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-content: center;
  align-items: center;
  background: #ffffff;
  border-radius: 8px;
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
  flex-shrink: 0;
  padding: 1px 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.filter-form {
  box-shadow: none !important;
  margin: 0;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  gap: 16px;
}

.filter-form .el-form-item {
  margin-bottom: 0;
  margin-right: 0;
}

.filter-form .el-form-item label {
  font-weight: 500;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .failed-messages {
    padding: 12px;
  }

  .header-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
    text-align: center;
    margin-bottom: 12px;
    padding: 12px 16px;
  }

  .header-actions h2 {
    font-size: 20px;
  }

  .filter-section {
    padding: 12px 16px;
    margin-bottom: 12px;
  }

  .filter-form {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .filter-form .el-form-item {
    width: 100%;
  }

  .el-table {
    margin-bottom: 8px;
  }

  .empty-block {
    margin: 16px 0;
    padding: 30px 16px;
  }
}

.el-table {
  flex: 1;
  overflow: auto;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 12px;
}

.el-table :deep(.el-table__header) {
  background: #f8f9fa;
}

.el-table :deep(.el-table__header th) {
  background: #f8f9fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 2px solid #e4e7ed;
}

.el-table :deep(.el-table__row:hover) {
  background: #f0f9ff;
}

.el-table :deep(.el-button) {
  margin-right: 8px;
  border-radius: 6px;
  font-weight: 500;
}

.el-table :deep(.el-button:last-child) {
  margin-right: 0;
}

.el-table :deep(.el-tag) {
  border-radius: 12px;
  font-weight: 500;
  border: none;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 12px 0;
  flex-shrink: 0;
  background: #ffffff;
  border-top: 1px solid #e4e7ed;
  border-radius: 0 0 8px 8px;
  margin-top: -1px;
}

.empty-block {
  margin: 20px 0;
  text-align: center;
  background: #ffffff;
  padding: 40px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.message-body-preview {
  display: inline-block;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  color: #606266;
  padding: 4px 8px;
  background: #f8f9fa;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.message-body-preview:hover {
  color: #409eff;
  background: #ecf5ff;
}

.message-content-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  width: 100%;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
  display: block;
}

.message-content-cell:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc;
}

:deep(.el-select .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff;
}

:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-pagination) {
  --el-pagination-button-color: #606266;
  --el-pagination-hover-color: #409eff;
}

:deep(.el-pagination .btn-next),
:deep(.el-pagination .btn-prev) {
  border-radius: 6px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 6px;
  margin: 0 2px;
}

@media (max-width: 768px) {
  .failed-messages {
    height: auto;
  }

  .page-header {
    padding: 16px;
  }

  .page-header h2 {
    font-size: 20px;
  }

  .filter-section {
    padding: 16px;
  }

  .filter-form {
    flex-direction: column;
    gap: 12px;
  }

  .filter-form .action-buttons {
    margin-left: 0;
    align-self: stretch;
  }

  .message-body-preview {
    max-width: 120px;
  }

  .el-table :deep(.el-button) {
    margin-bottom: 4px;
  }

  .empty-block {
    padding: 40px 16px;
  }
}

@media (max-width: 480px) {
  .failed-messages {
    padding: 12px;
  }

  .page-header {
    padding: 12px;
  }

  .page-header h2 {
    font-size: 18px;
  }

  .filter-section {
    padding: 12px;
  }

  .filter-form .el-select {
    width: 100% !important;
  }

  .filter-form .action-buttons .el-button {
    width: 100%;
  }

  .message-body-preview {
    max-width: 80px;
  }

  .el-table :deep(.el-button) {
    width: 100%;
    margin-bottom: 8px;
  }
}
</style>